<?php


namespace App\Extensions\Column;


use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid\Displayers\AbstractDisplayer;

class Tooltip extends AbstractDisplayer
{
    public function display($callback = '', $config = [])
    {
        if ($callback instanceof \Closure) {
            $callback = $callback->bindTo($this->row);
            $title = call_user_func_array($callback, [$this->row]);
        } elseif ($callback && is_string($callback) && isset($this->row->$callback)) {
            $title = $this->row->$callback;
        } else {
            $title = '';
        }
        if (!$title) {
            return $this->value;
        }
        $type = strtolower(($config['type'] ?? 'text'));
        $position = strtolower(($config['position'] ?? 'right'));
        if ($type != 'text' || $position == 'fixed') {
            if ($type == 'markdown') {
                $title = view('markdown', ['value' => $title]);
            }
            return $this->tooltip($title, $config);
        }
        return <<<THML
<a href="javascript:void(0);" class="grid-column-help" data-toggle="tooltip" data-title="{$title}"
data-placement="{$position}" data-html="true">{$this->value}
</a>
THML;

    }

    protected function tooltip($title, $config): string
    {
        $key = md5($title);
        $class = $config['class'] ?? '';
        $position = $config['position'] ?? 'bottom';
        if ($position == 'fixed') {
            $class = $class ?: 'fixed-tooltip-container';
            Admin::script($this->fixedScript($key));
        } else {
            $adjustment = $config['adjustment'] ?? 10;
            Admin::script($this->script($key, $position, $adjustment));
        }
        $style = [
            'display: none',
            'white-space: normal',
        ];
        if(isset($config['max-width'])){
            $style[] = 'max-width:'.$config['max-width'];
        }
        $style = implode(';',$style);
        return <<<THML
<span class="tooltip-{$key}">
<div id="tooltip-container-{$key}" class="{$class}"  style="{$style}"><a>{$title}</a></div>
{$this->value}
</span>
THML;

    }

    protected function script($key, $position = 'bottom', $adjustment = 10): string
    {
        return <<<SCRIPT
 $('.tooltip-{$key}').toolbar({
        content: '#tooltip-container-{$key}',
        position: '{$position}',
        adjustment: {$adjustment}
    });
SCRIPT;
    }

    protected function fixedScript($key): string
    {
        return <<<SCRIPT

$(".tooltip-{$key}").mouseover(function(){
 $("#tooltip-container-{$key}").show();
});
$(".tooltip-{$key}").mouseout(function(){
 $("#tooltip-container-{$key}").hide();
});
SCRIPT;
    }
}
